import { PageData } from "@/util";
import { Table, Image, PaginationProps, Form, Select, Row, Col } from "antd";
import { DefaultOptionType } from "antd/lib/select";
import { ColumnProps } from "antd/lib/table";
import { cloneDeep, debounce } from "lodash";
import { SetStateAction, useCallback, useContext, useEffect, useRef, useState } from "react";
import { getAdmin, getSource, GetSourceParams } from "src/api";
import AreaSelect from "src/components/dataEntry/AreaSelect";
import EllipsisText from "@/components/dataPresentation/EllipsisText";
import { AdminStatus, AdminGender } from "src/constant/admin";
import { AppContext } from "src/providers";
import { RoleRecord } from "../role/RoleType";
import { AdminRecord, FilterAdminKeys, FilterQuery } from "./AdminType";
const Admin = () => {
	const { REACT_APP_BASEURL } = useContext(AppContext);
	const columns: ColumnProps<AdminRecord>[] = [
		{
			dataIndex: "username",
			title: "用户名",
			width: 100,
			render: (text) => <EllipsisText>{text}</EllipsisText>,
		},
		{
			dataIndex: "roles",
			title: "角色",
			width: 100,
			render: (list = []) => <EllipsisText>{list.map((item: RoleRecord) => item.description).join()}</EllipsisText>,
		},
		{
			dataIndex: "gender",
			title: "性别",
			width: 100,
			render: (value: 0 | 1 | 2 = 0) => AdminGender[value],
		},
		{ dataIndex: "age", title: "年龄", width: 100 },
		{
			dataIndex: "status",
			title: "状态",
			width: 100,
			render: (value: 0 | 1) => AdminStatus[value] || "未知",
		},
		{ dataIndex: "mobile", title: "手机号", width: 100 },
		{ dataIndex: "email", title: "邮箱", width: 110 },
		{
			dataIndex: "avatar",
			title: "头像",
			width: 100,
			render: (src) => {
				if (!src) return null;
				return <Image src={`${REACT_APP_BASEURL}${src}`} width="36px" />;
			},
		},
		{
			dataIndex: "description",
			title: "描述",
			width: 100,
			render: (text) => <EllipsisText>{text}</EllipsisText>,
		},
		{ dataIndex: "city", title: "城市", width: 100 },
		{
			dataIndex: "createdTime",
			title: "创建时间",
			width: 100,
			render: (time) => new Date(time).toLocaleString(),
		},
		{
			dataIndex: "updatedTime",
			title: "更新时间",
			width: 100,
			render: (time) => new Date(time).toLocaleString(),
		},
	];
	const [dataSource, setDataSource] = useState<AdminRecord[]>([]);
	const [listLoading, setListLoading] = useState(true);
	const initialPagination = {
		pageSize: 10,
		current: 1,
		total: 0,
		onChange(current: number, pageSize: number) {
			paginationRef.current.pageSize = pageSize;
			paginationRef.current.current = current;
			setPagination(cloneDeep(paginationRef.current));
			fetchAdmin();
		},
	};
	const filterObjRef = useRef<Partial<Pick<AdminRecord, FilterAdminKeys>> | { [x: string]: unknown }>({});
	const [pagination, setPagination] = useState<PaginationProps>(cloneDeep(initialPagination));
	const paginationRef = useRef<PaginationProps>(cloneDeep(initialPagination));
	const [usernameOptions, setUsernameOptions] = useState<DefaultOptionType[]>([]);
	const [mobileOptions, setMobileOptions] = useState<DefaultOptionType[]>([]);
	const [emailOptions, setEmailOptions] = useState<DefaultOptionType[]>([]);
	const [roleOptions, setRoleOptions] = useState<DefaultOptionType[]>([]);
	const fetchAdmin = async () => {
		setListLoading(true);
		try {
			const result = await getAdmin({
				page: paginationRef.current.current,
				pageSize: paginationRef.current.pageSize,
				lookup: {
					localField: "roles",
					foreignField: "_id",
					from: "roles",
					as: "roles",
				},
				...filterObjRef.current,
			});
			const { total = 0, data } = result.data || {};
			paginationRef.current.total = total;
			setPagination(cloneDeep(paginationRef.current));
			setDataSource(data || []);
		} finally {
			setListLoading(false);
		}
	};
	const handleCommonSearch = async (
		key: FilterAdminKeys,
		value: string,
		setHandler: (value: SetStateAction<DefaultOptionType[]>) => void
	) => {
		const query: FilterQuery = {};
		if (value) query[key] = { like: true, value };
		const result = await getAdmin(query);
		const { data = [] } = result.data || {};
		setHandler(
			data.map((item) => ({
				label: item[key],
				value: String(item[key]).replaceAll("'", ""),
			}))
		);
	};
	const searchUserName = async (username = "") => {
		handleCommonSearch("username", username, setUsernameOptions);
	};
	const searchMobile = async (mobile = "") => {
		handleCommonSearch("mobile", mobile, setMobileOptions);
	};
	const searchEmail = async (email = "") => {
		handleCommonSearch("email", email, setEmailOptions);
	};
	const searchUserNameDebounce = useCallback(debounce(searchUserName, 300), []);
	const searchMobileDebounce = useCallback(debounce(searchMobile, 300), []);
	const searchEmailDebounce = useCallback(debounce(searchEmail, 300), []);
	const handleCommonSelectChange = (key: FilterAdminKeys, value: string | number | undefined) => {
		if (value === undefined) {
			delete filterObjRef.current[key];
		} else {
			if (key === "roles") {
				filterObjRef.current[key] = { in: true, value: [value] };
			} else {
				filterObjRef.current[key] = value;
			}
		}
		fetchAdmin();
	};
	const searchRole = async (description = "") => {
		const params: GetSourceParams = {
			source: "role",
			page: 1,
			pageSize: 9999,
		};
		if (description)
			params.description = {
				like: true,
				value: description.replaceAll("'", ""),
			};
		const res = await getSource<PageData<Pick<RoleRecord, "description" | "_id">[]>>(params);
		setRoleOptions(
			res.data?.data.map((item) => ({
				label: item.description,
				value: item._id,
			})) || []
		);
	};
	const searchRoleDebounce = useCallback(debounce(searchRole, 300), []);
	useEffect(() => {
		fetchAdmin();
		searchUserName();
		searchMobile();
		searchEmail();
		searchRole();
	}, []);
	return (
		<>
			<Form>
				<Row gutter={24}>
					<Col span={6}>
						<Form.Item name="username">
							<Select
								allowClear
								showSearch
								placeholder="选择或搜索用户名"
								onSearch={searchUserNameDebounce}
								onChange={(value: string) => handleCommonSelectChange("username", value)}
								options={usernameOptions}
								onClear={searchUserName}
							/>
						</Form.Item>
					</Col>
					<Col span={6}>
						<Form.Item name="status">
							<Select
								allowClear
								placeholder="选择或搜索状态"
								onChange={(value: number) => handleCommonSelectChange("status", value)}
							>
								<Select.Option value={1}>可用</Select.Option>
								<Select.Option value={0}>冻结</Select.Option>
							</Select>
						</Form.Item>
					</Col>
					<Col span={6}>
						<Form.Item name="mobile">
							<Select
								onSearch={searchMobileDebounce}
								allowClear
								showSearch
								placeholder="选择或搜索手机号"
								options={mobileOptions}
								onChange={(value: string) => handleCommonSelectChange("mobile", value)}
								onClear={searchMobile}
							/>
						</Form.Item>
					</Col>
					<Col span={6}>
						<Form.Item name="email">
							<Select
								onSearch={searchEmailDebounce}
								allowClear
								showSearch
								placeholder="选择或搜索邮箱"
								onChange={(value: string) => handleCommonSelectChange("email", value)}
								options={emailOptions}
								onClear={searchEmail}
							></Select>
						</Form.Item>
					</Col>
				</Row>
				<Row gutter={24}>
					<Col span={6}>
						<Form.Item name="city">
							<AreaSelect
								onChange={(value: string) => handleCommonSelectChange("city", value)}
								placeholder="选择或搜索地区"
							/>
						</Form.Item>
					</Col>
					<Col span={6}>
						<Form.Item name="role">
							<Select
								allowClear
								showSearch
								filterOption={false}
								onSearch={searchRoleDebounce}
								onClear={searchRole}
								placeholder="选择或搜索角色"
								onChange={(value: string) => handleCommonSelectChange("roles", value)}
								options={roleOptions}
							/>
						</Form.Item>
					</Col>
					<Col span={12}>
						<Row></Row>
					</Col>
				</Row>
			</Form>
			<Table
				columns={columns}
				dataSource={dataSource.map((item) => ({
					...item,
					key: item._id,
				}))}
				loading={listLoading}
				pagination={pagination}
				scroll={{
					x: "2100px",
					y: "calc(100vh - 64px - 24px * 2 - 16px * 2 - 32px - 90px)",
				}}
			/>
		</>
	);
};

export default Admin;
